#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <string>
#include <cstdio>
#include <cstdlib>

using namespace std;

string ToHex(pthread_t tid)
{
  char id[64];
  snprintf(id, sizeof(id), "0x%lx", tid);
  return id;
}

// void *Routine(void *arg)
// {
//   while (1)
//   {
//     cout << "new thread tid: " << pthread_self() << ",toHex : " << ToHex(pthread_self()) << endl;
//     sleep(1);
//   }
// }
// int main()
// {
//   pthread_t tid;
//   pthread_create(&tid, NULL, Routine, NULL);
//   while (1)
//   {
//     // cout << "new thread tid: " << tid << endl;
//     cout << "main thread tid: " << pthread_self() << ",toHex : " << ToHex(pthread_self()) << endl;
//     sleep(1);
//   }
//   return 0;
// }

__thread uint64_t starttime = 0;

void *threadrun1(void *args)
{
  starttime = time(nullptr);
  pthread_detach(pthread_self());
  std::string name = static_cast<const char *>(args);

  while (true)
  {
    sleep(1);
    printf("%s, starttime: %lu, &starttime: %p\n", name.c_str(), starttime, &starttime);
  }

  return nullptr;
}

void *threadrun2(void *args)
{
  sleep(3);
  starttime = time(nullptr);

  pthread_detach(pthread_self());
  std::string name = static_cast<const char *>(args);

  while (true)
  {
    printf("%s, starttime: %lu, &starttime: %p\n", name.c_str(), starttime, &starttime);
    sleep(1);
  }

  return nullptr;
}

int main()
{
  pthread_t tid1;
  pthread_t tid2;
  pthread_create(&tid1, nullptr, threadrun1, (void *)"thread 1");
  pthread_create(&tid2, nullptr, threadrun2, (void *)"thread 2");

  int cnt = 5;
  while (true)
  {
    if (!(cnt--))
      break;
    std::cout << "I am a main thread ..." << getpid() << std::endl;
    sleep(1);
  }

  return 0;
}